package handler

import (
	"docu-flow/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Create(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	data := model.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
	}
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offest := (page - 1) * size
	var article []model.Article
	err := model.DB.Debug().Find(&article).Limit(size).Offset(offest).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "展示成功",
			"data": article,
		})
	}
}

func Data(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	err := model.DB.Debug().Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "展示成功",
			"data": article,
		})
	}
}
